#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> storage;
    void inorderTraval(TreeNode* root)
    {
        if (!root) return;
        inorderTraval(root->left);
        storage.push_back(root->val);
        inorderTraval(root->right);
    }
    TreeNode* makeBST(int left, int right)
    {
        if (left > right) return nullptr;
        int mid = (right - left) / 2 + left;
        TreeNode* root = new TreeNode(storage[mid], makeBST(left, mid - 1), makeBST(mid + 1, right));
        return root;
    }
    TreeNode* balanceBST(TreeNode* root) {
        inorderTraval(root);
        return makeBST(0, storage.size() - 1);
    }
};